import aiofiles
import os
import time
from datetime import datetime, timedelta
from typing import Annotated, Literal, Union
from uuid import UUID

import uvicorn
from fastapi import FastAPI, Path, Query, Body, Cookie, Header, status, Form, File, UploadFile, HTTPException,Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, get_redoc_html
from fastapi.responses import HTMLResponse,JSONResponse,PlainTextResponse
from starlette.staticfiles import StaticFiles
from pydantic import BaseModel, Field, HttpUrl, EmailStr

# 创建FastAPI实例，禁用掉FastAPI会自动生成Swagger UI和Redoc文档
app = FastAPI(docs_url=None, redoc_url=None)

# 静态文件挂载（路由与静态文件映射）
app.mount("/static", StaticFiles(directory="../statics"), name="static")


# 重新提供一个Swagger UI，相当于我们自己重写了这么一个路由
@app.get("/docs", include_in_schema=False)
def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url = "/openapi.json",
        title = "Swagger UI for FastAPI",
        swagger_js_url="/static/swagger-ui-bundle.min.js",
        swagger_css_url="/static/swagger-ui.min.css"
    )

items = {"手机": "这是一个手机信息"}

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    # 传递的名称中包含传入的字符串的信息（模糊匹配）形成一个列表
    results = [{key:value} for key,value in items.items() if item_id in key]
    if not results:
        raise HTTPException(status_code=404, detail="未找到相应的item")
    return results

@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
    results = [{key:value} for key,value in items.items() if item_id in key]
    if not results:
        raise HTTPException(status_code=404, detail="未找到相应的item", headers={"X-Error": "header error"})
    return results


class UniqueOrderNoException(Exception):
    def __init__(self, msg: str):
        self.msg = msg

@app.exception_handler(UniqueOrderNoException)
async def unique_order_no_exception_handler(request:Request, exc):
    return JSONResponse(
        status_code=418,
        content={"message": exc.msg},
    )

class Order(BaseModel):
    order_no: str
    order_amount: float

@app.post("/order")
async def create_order(order: Order):

    if order.order_no == "123456":
        raise UniqueOrderNoException("订单号重复")
    return {"message": "订单创建成功"}


@app.get("/order")
async def get_order(order_no: int):
    if order_no == 1:
        raise HTTPException(status_code=418, detail="订单号不可以为1")
    return {"message": "订单查询成功"}

# 覆盖RequestValidationError的异常处理逻辑
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail":exc.errors(),"body":exc.body}),
    )

@app.post("/order/create")
async def create_order(order_no: Annotated[int, Body(gt=1000)]):
    return {"message": "订单创建成功"}


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return PlainTextResponse(status_code=exc.status_code, content=exc.detail)






if __name__ == '__main__':
    app.debug = True
    uvicorn.run("main:app", host="127.0.0.1", port=8020, reload=True)

